package com.journey.org.ui.search.gank

import android.annotation.SuppressLint
import android.app.Application
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.viewModelScope
import com.journey.org.BR
import com.journey.org.R
import com.mvvmhabit.org.base.BaseViewModel
import com.mvvmhabit.org.binding.command.BindingAction
import com.mvvmhabit.org.binding.command.BindingCommand
import com.mvvmhabit.org.binding.command.BindingConsumer
import com.mvvmhabit.org.bus.Messenger
import com.mvvmhabit.org.custom.LoadingLayout
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import me.tatarka.bindingcollectionadapter2.ItemBinding

/**
 * @Date: 2020/11/19 10:46
 * @Author:小妖
 * @Description: 干货-搜索
 */
class GankSearchViewModel(application: Application) : BaseViewModel(application) {

    val requestStateField = ObservableInt()

    val onClickAgainLoadCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            onPageField.set(1)
            loadGankSearchContent(onSearchContentField.get()!!)
        }
    })

    companion object {
        const val TOKEN_SEARCH_CONTENT = "search_content"
    }

    override fun onCreate() {
        super.onCreate()
        // 注册接收搜索内容
        Messenger.getDefault().register(
            this,
            TOKEN_SEARCH_CONTENT,
            String::class.java,
            object : BindingConsumer<String> {
                override fun call(t: String) {
                    onSearchContentField.set(t)
                    loadGankSearchContent(t)
                }
            })
    }

    // 搜索类型
    val onSearchTypeField = ObservableField<String>("")

    val onSearchContentField = ObservableField<String>("")

    private val onPageField = ObservableInt(1)

    val onRefreshCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            onPageField.set(1)
            loadGankSearchContent(onSearchContentField.get()!!)
        }
    })

    val onLoadMoreCommand = BindingCommand<Any>(object : BindingAction {
        override fun call() {
            onPageField.set(onPageField.get() + 1)
            loadGankSearchContent(onSearchContentField.get()!!)
        }
    })

    val itemBinding =
        ItemBinding.of<GankSearchItemViewModel>(BR.viewModel, R.layout.gank_search_item)

    val items = ObservableArrayList<GankSearchItemViewModel>()


    @SuppressLint("CheckResult")
    fun loadGankSearchContent(searchContent: String) {
        viewModelScope.launch(Dispatchers.Main) {
            if (onPageField.get() == 1) {
                items.clear()
                requestStateField.set(LoadingLayout.NETWORK_LOADING)
            }

        }
    }
}